<template>
  <q-dialog
    no-backdrop-dismiss
    v-model="recordDetailVisible"
    square
    position="standard"
  >
    <q-card style="width: 800px; max-width: 80vw">
      <q-card-section class="row items-center q-pb-none">
        <div class="text-h6">
          {{ formTypeName }} {{ $t("Sql") }}:
          {{ recordDetail.value.sql_code }}
        </div>
        <q-space />
        <q-btn icon="close" flat round dense v-close-popup />
      </q-card-section>

      <q-separator />

      <q-card-section>
        <q-form ref="recordDetailForm">
          <div class="col">
            <div class="row">
              <q-field class="col" :label="$t('Sql') + $t('Type')" stack-label>
                <template v-slot:control>
                  <q-option-group
                    v-model="recordDetail.value.sql_type"
                    :options="dictOptions.sqlType"
                    color="primary"
                    inline
                    @update:model-value="handleSqlTypeChange"
                  >
                  </q-option-group>
                </template>
              </q-field>
            </div>
            <div class="row">
              <q-input
                class="col q-mr-md"
                filled
                v-model="recordDetail.value.sql_code"
                :label="$t('Sql') + $t('Code') + '(' + $t('English') + ')'"
                :rules="[
                  (val) => (val && val.length > 0) || '必须输入SQL编码',
                  (val) =>
                    /[A-Z]/.test(val) == false || 'SQL编码不能包含大写字母',
                ]"
              />

              <q-input
                class="col"
                filled
                v-model="recordDetail.value.memo"
                :label="$t('Memo')"
              />
            </div>
            <div class="row">
              <q-input
                class="col"
                v-if="recordDetail.value.sql_type === 'query'"
                filled
                type="textarea"
                v-model="recordDetail.value.sql_string"
                @change="passed = false"
                :label="$t('Sql') + $t('Statement')"
                :rules="[(val) => (val && val.length > 0) || '必须输入SQL语句']"
              >
              </q-input>
              <span class="col" v-else>
                <div class="row">
                  <q-input
                    class="col q-mr-md"
                    filled
                    @change="passed = false"
                    v-model="recordDetail.value.schema_name"
                    :label="$t('Schema') + $t('Name')"
                  />
                  <q-input
                    class="col"
                    filled
                    @change="passed = false"
                    v-model="recordDetail.value.table_name"
                    :label="$t('Table') + $t('Name')"
                  />
                  <q-checkbox
                    class="col"
                    v-model="recordDetail.value.has_day_id"
                    label="是否包含day_id"
                    true-value="yes"
                    false-value="no"
                    left-label
                  />
                </div>
              </span>
            </div>
          </div>
        </q-form>
      </q-card-section>
      <q-separator />
      <q-card-actions align="right">
        <q-btn
          v-if="recordDetail.value.sql_type === 'query'"
          push
          color="secondary"
          @click="validateSql"
          :label="$t('Validate') + $t('Sql') + $t('Statement')"
        />
        <q-btn
          v-else
          push
          color="secondary"
          @click="validatePreDefinedTable"
          :label="$t('Validate') + $t('Pre') + $t('Define') + $t('Table')"
        />

        <q-btn
          :label="t('Save')"
          color="primary"
          @click="handleAddOrEditAfterPassed"
        />
        <q-btn :label="t('Cancel')" color="negative" v-close-popup />
      </q-card-actions>

      <q-inner-loading :showing="loading">
        <q-spinner-gears size="50px" color="primary" />
      </q-inner-loading>
    </q-card>
  </q-dialog>
</template>

<script setup>
import useRecordDetail from "src/composables/useRecordDetail";
import { postAction } from "src/utils/requestAction";
import { useStorageStore } from "src/stores/storage";
import { computed, onMounted, ref, watch } from "vue";
import { useQuasar } from "quasar";
import { useI18n } from "vue-i18n";

const $q = useQuasar();
const { t } = useI18n();
const emit = defineEmits(["handleFinish"]);
const passed = ref(false);
const url = {
  add: "sql/add-sql",
  edit: "sql/edit-sql",
  queryById: "sql/query-sql-by-id",
  validateSql: "sql/validate-sql",
  validatePreDefinedTable: "sql/validate-pre-defined-table",
};

const defaults = {
  sql_code: "",
  sql_type: "query",
  schema_name: "",
  table_name: "",
  sql_string: "",
  memo: "",
  has_day_id: "no",
};

const getSqlParams = async () => {
  const res = await postAction("sqlparam/get-sqlparam-list", {});
  const sqlParams = [];
  console.log(res);
  if (res.code === 1) {
    res.data.records.forEach((item) => {
      sqlParams.push({
        id: item.id,
        sqlparam_code: item.sqlparam_code,
        sqlparam_name: item.sqlparam_name,
      });
    });
  }
  return sqlParams;
};

const sqlParams = ref([]);

onMounted(async () => {
  sqlParams.value = await getSqlParams();
  console.log(sqlParams.value);
});

const {
  dictOptions,
  formType,
  formTypeName,
  recordDetail,
  recordDetailVisible,
  loading,
  show,
  recordDetailForm,
  handleAddOrEdit,
} = useRecordDetail(url, emit, defaults);

defineExpose({
  show,
  formType,
  recordDetail,
});

const validateSql = async () => {
  const sql_string = recordDetail.value.sql_string;
  const sqlParams = {
    sql_string,
  };
  await postAction(url.validateSql, sqlParams).then((res) => {
    //console.log(res);
    passed.value = res.code === 1 ? true : false;
    $q.dialog({
      title: "测试结果",
      message: res.code === 1 ? "测试Sql通过!" : res.message,
    });
  });
};

const validatePreDefinedTable = async () => {
  const schema_name = recordDetail.value.schema_name;
  const table_name = recordDetail.value.table_name;
  const sql_type = recordDetail.value.sql_type;
  const has_day_id = recordDetail.value.has_day_id;
  const sqlParams = {
    schema_name: schema_name,
    table_name: table_name,
    sql_type: sql_type,
    has_day_id: has_day_id,
  };
  await postAction(url.validatePreDefinedTable, sqlParams).then((res) => {
    //console.log(res);
    passed.value = res.code === 1 ? true : false;
    $q.dialog({
      title: "测试结果",
      message: res.code === 1 ? "测试预定义表通过!" : res.message,
    });
  });
};

const handleAddOrEditAfterPassed = () => {
  if (passed.value) {
    handleAddOrEdit();
  } else {
    $q.dialog({
      title: "需要校验SQL",
      message: "尚未通过校验或上次校验后修改了SQL, 请先测试SQL是否合法!",
    });
  }
};

const handleSqlTypeChange = (val) => {
  recordDetail.value.sql_string = "";
  recordDetail.value.table_name = "";
  recordDetail.value.schema_name = "";
  recordDetail.value.has_day_id = null;
  passed.value = false;
};
</script>

<script>
import { defineComponent } from "vue";

export default defineComponent({
  name: "SqlRecordDetail",
});
</script>
